<template>
  <div class="popup-container">
    <div class="popup-header">
      <h3>地图定位</h3>
      <button class="close-btn" @click="$emit('close')">×</button>
    </div>
    <div class="popup-content">
      <div class="map-container">
        <div id="coordinate-map-container"></div>
      </div>
      <div class="info-box">
        <div class="search-container">
          <input
            v-model="keywords"
            type="text"
            placeholder="请输入关键词"
            @input="onInput"
            class="search-input"
          />
          <ul class="options" v-if="options.length > 0">
            <li
              v-for="item in options"
              :key="item.id"
              @click="selectOption(item)"
              class="option"
            >
              <span>{{ item.name }}</span>
              <span class="district">{{ item.district }}</span>
            </li>
          </ul>
        </div>
        <div class="info-details">
          <p>纬度：{{ form.lat }}</p>
          <p>经度：{{ form.lng }}</p>
          <p>详细地址：{{ form.address }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "coordinate",
  data() {
    return {
      map: null,
      marker: null,
      geoCoder: null,
      AutoComplete: null,
      keywords: "",
      form: {
        lng: "",
        lat: "",
        address: "",
        adcode: "",
      },
      loading: false,
      options: [],
    };
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("coordinate-map-container", {
            viewMode: "2D",
            zoom: 10, // Increased zoom level for better visibility
            center: [105.602725, 37.076636],
          });
          this.geoCoder = new AMap.Geocoder({ city: "010", radius: 1000 });
          this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
          this.map.on("click", (e) => {
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            this.removeMarker();
            this.setMapMarker();
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },

    currentSelect(val) {
      if (!val || !val.location) {
        console.error('Invalid selection: val or val.location is undefined');
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: `${val.district} ${val.address}`,
        adcode: val.adcode,
      };
      this.removeMarker();
      this.setMapMarker();
    },

    setMapMarker() {
      if (!this.map || !this.form.lng || !this.form.lat) return;

      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },

    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null;
      }
    },

    toGeoCoder() {
      const lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
        }
      });
    },

    onInput() {
      if (this.keywords !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(this.keywords, (status, result) => {
            if (status === 'complete' && result.tips) {
              this.options = result.tips;
            } else {
              this.options = [];
            }
          });
        }, 200);
      } else {
        this.options = [];
      }
    },

    selectOption(val) {
      if (!val || !val.location) {
        console.error('Invalid selection: val or val.location is undefined');
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: `${val.district} ${val.address}`,
        adcode: val.adcode,
      };
      this.options = [];
      this.removeMarker();
      this.setMapMarker();
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>

<style scoped>
.popup-container {
  position: relative;
  width: 800px;
  height: 600px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f1f1f1;
  border-bottom: 1px solid #ddd;
}

.close-btn {
  border: none;
  background: transparent;
  font-size: 24px;
  cursor: pointer;
}

.popup-content {
  display: flex;
  flex: 1;
  padding: 10px;
}

.map-container {
  flex: 2;
  position: relative;
}

#coordinate-map-container {
  width: 100%;
  height: 100%;
  border: 1px solid #ddd;
}

.info-box {
  flex: 1;
  padding: 10px;
  border-left: 1px solid #ddd;
  overflow: hidden; /* Prevents content from overflowing */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.search-container {
  margin-bottom: 10px;
}

.search-input {
  width: 100%;
  padding: 5px;
}

.options {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  list-style-type: none;
  padding: 0;
  margin: 0;
  max-height: 150px;
  overflow-y: auto;
}

.option {
  padding: 5px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option:hover {
  background-color: #f5f5f5;
}

.district {
  color: #8492a6;
  font-size: 13px;
}
</style>
